package com.example.drugaiservice.service.impl;

import com.example.drugaiservice.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void preHeatZSet() {
        log.info("开始预热数据");
        if (redisTemplate.opsForValue().get("symptomPreHeat").equals("1")) {
            redisTemplate.opsForValue().setIfAbsent("symptomPreHeat", "1");
            ZSetOperations zSet = redisTemplate.opsForZSet();
            zSet.removeRange("symptom", 0, Integer.MAX_VALUE);
            zSet.add("symptom", "有点发烧", 1000);
            zSet.add("symptom", "肚子不舒服", 1000);
            zSet.add("symptom", "胳膊疼", 999);
            zSet.add("symptom", "头晕目眩", 1000);
            zSet.add("symptom", "口干舌燥", 1000);
            zSet.add("symptom", "吃饭没有胃口", 987);
            zSet.add("symptom", "拉肚子", 1000);
            zSet.add("symptom", "上火", 1000);
            zSet.add("symptom", "嘴里长了个包", 1000);
            zSet.add("symptom", "最近一直犯困", 1000);
        }
    }

    @Override
    public void rankAddWithZSet(String value) {
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.incrementScore("symptom", value, 1); //每次访问+1
    }

    @Override
    public Set<String> getTop10ByZSet() {
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        Set symptom = zSetOperations.reverseRangeWithScores("symptom", 0, 9);
        //symptom.stream().map(symptom1 -> symptom1.toString()).collect(Collectors.toSet());
        return symptom;
    }

    @Override
    public void clearRedis() {
        Set<String> keys = redisTemplate.keys("*");
        int i = 1;
        if (keys != null) {
            redisTemplate.delete(keys);
            i++;
        }
        log.info(i + "条数据已被清理");
    }
}
